//
//  BEFileExtension.swift
//  BasicExtensions
//
//  Created by 范晓鑫 on 2022/12/12.
//

import Foundation

extension FileManager {
    /// 如果目录不存在则创建
    public func createDirectoryIfNotExists(at url: URL) throws {
        if #available(iOS 16.0, *) {
            try createDirectoryIfNotExists(atPath: url.path())
        } else {
            try createDirectoryIfNotExists(atPath: url.path)
        }
    }
    /// 如果目录不存在则创建
    public func createDirectoryIfNotExists(atPath path: String) throws {
        var isDirectory: ObjCBool = false
        let exist = FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory)
        if !exist || !isDirectory.boolValue {
            if exist {
                try FileManager.default.removeItem(atPath: path)
            }
            try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true)
        }
    }
}
extension Data {
    /// 写入文件并自动创建不存在的目录
    public func wirteAndCreateDirectories(to url: URL, options: Data.WritingOptions = []) throws {
        let directory = url.deletingLastPathComponent()
        try FileManager.default.createDirectoryIfNotExists(at: directory)
        try self.write(to: url, options: options)
    }
}
